package rs.mbs2.epics.server.servlet;

import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import rs.mbs2.epics.server.entity.Comment;
import rs.mbs2.epics.server.entity.Photo;
import rs.mbs2.epics.server.session.dao.localinterface.CommentDaoLocal;
import rs.mbs2.epics.server.session.dao.localinterface.PhotoDaoLocal;

@SuppressWarnings("serial")
public class DeleteCommentController extends HttpServlet {
	
	private static Logger log = Logger.getLogger(DeleteCommentController.class);

	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private CommentDaoLocal commentDao;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
//		System.out.println("DeleteCommentController.doGet()");
		
		String photoIdString = request.getParameter("photoId");
		Integer photoId = Integer.parseInt(photoIdString);
		
		String commentIdString = request.getParameter("commentId");
		Integer commentId = Integer.parseInt(commentIdString);
		
		Photo photo = photoDao.findById(photoId);
		
		for(Comment comment : photo.getComments()) {
//			System.out.println("Komentar: " + comment.getContents());
			if(comment.getId().equals(commentId)) {
				photo.getComments().remove(comment);
				commentDao.remove(comment);
				break;
			}
		}
		
		photoDao.merge(photo);
		
		log.info(new Date() + " obrisan komentar[id]:" + commentIdString);
		getServletContext().getRequestDispatcher("/ViewPhotoController?id=" + photoId).forward(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
}
